package com.service.impl;

import com.dao.mapper.PasswordLogMapper;
import com.dao.mapper.TokenLogMapper;
import com.dao.pojo.PasswordLog;
import com.dao.pojo.TokenLog;
import com.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private PasswordLogMapper passwordLogMapper;

    @Autowired
    TokenLogMapper tokenLogMapper;

    @Override
    public boolean register(String email, String password) {
        List<PasswordLog> userPasswords = passwordLogMapper.findUserPassword(email);
        if (userPasswords.size()!=0){
           return false;
        }else {
            PasswordLog passwordLog = new PasswordLog();
            passwordLog.setEmail(email);
            passwordLog.setPassword(password);
            passwordLogMapper.insertPassword(passwordLog);
        }
        return true;
    }

    @Override
    public boolean isRegistered(String email) {
        try {
            return passwordLogMapper.findUserPassword(email).size()>0;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public String login(String email, String password) {
        if (!checkPassword(email, password)){
            return "false";
        }
        return createToken(email);
    }

    @Override
    public String createToken(String email) {
        TokenLog tokenLog = null;
        List<TokenLog> logs = tokenLogMapper.findUserCodeByEmail(email);
        if (logs.size()>0){
            tokenLog = logs.get(0);
            tokenLog.setToken(UUID.randomUUID().toString());
            tokenLogMapper.updateToken(tokenLog);
        }else {
            tokenLog = new TokenLog();
            tokenLog.setEmail(email);
            tokenLog.setToken(UUID.randomUUID().toString());
            tokenLogMapper.insertToken(tokenLog);
        }
        return tokenLog.getToken();
    }

    @Override
    public String info(String token) {
        List<TokenLog> tokenLog = tokenLogMapper.findUserCodeByToken(token);
        return tokenLog.get(0).getEmail();
    }

    @Override
    public boolean checkPassword(String email, String password) {
        List<PasswordLog> logs = passwordLogMapper.findUserPassword1(email, password);
        return logs.size()>0;
    }

}
